﻿
//描 述：基础操作类--top 是Window默认的全局变量，在全局变量上扩展操作对象
top.ibpm = (function ($) {
    "use strict";   //严格模式
    var ibpm = {
        // 是否是调试模式
        isDebug: true,
        log: function () {
            if (ibpm.isDebug) {
                console.log('=====>' + new Date().getTime() + '<=====');
                var len = arguments.length;
                for (var i = 0; i < len; i++) {
                    console.log(arguments[i]);
                }
            }
        },
        //客户端语言包加载（菜单，tab条）
        language: {
            getMainCode: function () {
                return 'cn';
            },
            get: function (text, callback) {
                callback(text);
            },
            getSyn: function (text) {
                return text;
            }
        },
        // 创建一个GUID
        newGuid: function () {
            var guid = "";
            for (var i = 1; i <= 32; i++) {
                var n = Math.floor(Math.random() * 16.0).toString(16);
                guid += n;
                if ((i == 8) || (i == 12) || (i == 16) || (i == 20)) guid += "-";
            }
            return guid;
        },
        // 加载数据进度
        loadbarInit: function () {
            var _html = '<div class="M-loading-bar" id="M_loading_bar" style="display: none;">';
            _html += '<div class="M-loading-bar-bg"></div>';
            _html += '<div class="M-loading-bar-message" id="M_loading_bar_message"></div>';
            _html += '</div>';
            $('#M_form_bg').append(_html);
        },
        // 加载提示
        loading: function (isShow, _text) {//加载动画显示与否
            var $loading = top.$("#M_loading_bar");
            if (!!_text) {
                top.ibpm.language.get(_text, function (text) {
                    top.$("#M_loading_bar_message").html(text);
                });
            } else {
                top.ibpm.language.get("正在拼命加载中．．．", function (text) {
                    top.$("#M_loading_bar_message").html(text);
                });
            }
            if (isShow) {
                $('#M_form_bg').show();
                $loading.show();
            } else {
                $('#M_form_bg').hide();
                $loading.hide();
            }
        },
        // 获取iframe窗口
        iframe: function (Id, _frames) {
            if (_frames[Id] != undefined) {
                if (_frames[Id].contentWindow != undefined) {
                    return _frames[Id].contentWindow;   //获取到里面的DOM元素
                }
                else {
                    return _frames[Id];
                }
            }
            else {
                return null;
            }
        },
        // 改变url参数值
        changeUrlParam: function (url, key, value) {
            var newUrl = "";
            var reg = new RegExp("(^|)" + key + "=([^&]*)(|$)");
            var tmp = key + "=" + value;
            if (url.match(reg) != null) {
                newUrl = url.replace(eval(reg), tmp);
            } else {
                if (url.match("[\?]")) {
                    newUrl = url + "&" + tmp;
                }
                else {
                    newUrl = url + "?" + tmp;
                }
            }
            return newUrl;
        },
        // 转化成十进制
        toDecimal: function (num) {
            if (num == null) {
                num = "0";
            }
            num = num.toString().replace(/\$|\,/g, '');
            if (isNaN(num))
                num = "0";
            var sign = (num == (num = Math.abs(num)));
            num = Math.floor(num * 100 + 0.50000000001);
            var cents = num % 100;
            num = Math.floor(num / 100).toString();
            if (cents < 10)
                cents = "0" + cents;
            for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
                num = num.substring(0, num.length - (4 * i + 3)) + '' +
                    num.substring(num.length - (4 * i + 3));
            return (((sign) ? '' : '-') + num + '.' + cents);
        },
        // 文件大小转换
        countFileSize: function (size) {
            if (size < 1024.00)
                return ibpm.toDecimal(size) + " 字节";
            else if (size >= 1024.00 && size < 1048576)
                return ibpm.toDecimal(size / 1024.00) + " KB";
            else if (size >= 1048576 && size < 1073741824)
                return ibpm.toDecimal(size / 1024.00 / 1024.00) + " MB";
            else if (size >= 1073741824)
                return ibpm.toDecimal(size / 1024.00 / 1024.00 / 1024.00) + " GB";
        },
        // 数组复制
        arrayCopy: function (data) {
            return $.map(data, function (obj) {
                return $.extend(true, {}, obj);
            });
        },
        // 检测数据是否选中
        checkrow: function (id, txt) {
            var isOK = true;
            if (txt == undefined || txt == "" || txt == 'null' || txt == 'undefined') {
                txt = '您没有选中任何数据项,请选中后再操作！';
            }
            if (id == undefined || id == "" || id == 'null' || id == 'undefined') {
                isOK = false;
                top.ibpm.language.get(txt, function (text) {
                    ibpm.alert.warning(text);
                });
            }
            return isOK;
        },
        // 提示消息栏
        alert: {
            success: function (msg) {
                top.ibpm.language.get(msg, function (text) {
                    toastr.success(text);
                });
            },
            info: function (msg) {
                top.ibpm.language.get(msg, function (text) {
                    toastr.info(text);
                });
            },
            warning: function (msg) {
                top.ibpm.language.get(msg, function (text) {
                    toastr.warning(text);
                });
            },
            error: function (msg) {
                top.ibpm.language.get(msg, function (text) {
                    toastr.warning(msg);
                });
            }
        },
        //下载文件（she写的扩展）
        download: function (options) {
            var defaults = {
                method: "GET",
                url: "",
                param: []
            };
            var options = $.extend(defaults, options);
            if (options.url && options.param) {
                var $form = $('<form action="' + options.url + '" method="' + (options.method || 'post') + '"></form>');
                for (var key in options.param) {
                    var $input = $('<input type="hidden" />').attr('name', key).val(options.param[key]);
                    $form.append($input);
                }
                $form.appendTo('body').submit().remove();
            };
        },
        // 数字格式转换成千分位
        commafy: function (num) {
            if (num == null) {
                num = "0";
            }
            if (isNaN(num)) {
                return "0";
            }
            num = num + "";
            if (/^.*\..*$/.test(num)) {
                varpointIndex = num.lastIndexOf(".");
                varintPart = num.substring(0, pointIndex);
                varpointPart = num.substring(pointIndex + 1, num.length);
                intPart = intPart + "";
                var re = /(-?\d+)(\d{3})/
                while (re.test(intPart)) {
                    intPart = intPart.replace(re, "$1,$2")
                }
                num = intPart + "." + pointPart;
            } else {
                num = num + "";
                var re = /(-?\d+)(\d{3})/
                while (re.test(num)) {
                    num = num.replace(re, "$1,$2")
                }
            }
            return num;
        },
        // 检测图片是否存在
        isExistImg: function (pathImg) {
            if (!!pathImg) {
                var ImgObj = new Image();
                ImgObj.src = pathImg;
                if (ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0)) {
                    return true;
                } else {
                    return false;
                }
            }
            else {
                return false;
            }
        }
    };
    return ibpm;
})(window.jQuery);

//ajax操作方法--接着上面的基础定义，追加扩展
(function ($, ibpm) {
    "use strict";
    var httpCode = {
        success: 200,
        fail: 400,
        exception: 500
    };
    var exres = { code: httpCode.exception, info: '通信异常，请联系管理员！' }
    $.extend(ibpm, {
        // http 通信异常的时候调用此方法
        httpErrorLog: function (msg) {
            ibpm.log(msg);
        },
        // http请求返回数据码
        httpCode: httpCode,
        // get请求方法（异步）:url地址,callback回调函数
        httpAsyncGet: function (url, callback) {
            $.ajax({
                url: url,
                type: "GET",
                dataType: "json",
                async: true,
                cache: false,
                success: function (data) {
                    if (data.code == ibpm.httpCode.exception) {
                        ibpm.httpErrorLog(data.info);
                        ibpm.alert.error(data.info);
                    }
                    else if (data.code == ibpm.httpCode.fail) {
                        ibpm.httpErrorLog(data.info);
                        ibpm.alert.error(data.info);
                    }
                    else
                        callback(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    ibpm.httpErrorLog(textStatus);
                    ibpm.alert.warning(JSON.stringify(exres));
                },
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                },
                complete: function () {
                    ibpm.loading(false);
                }
            });
        },
        // get请求方法（同步）:url地址,param参数
        httpAsyncGetByParam: function (url, param, callback) {
            $.ajax({
                url: url,
                data: param,
                type: "GET",
                dataType: "json",
                async: true,
                cache: false,
                success: function (data) {
                    if (data.code == ibpm.httpCode.exception) {
                        ibpm.httpErrorLog(data.info);
                        ibpm.alert.error(data.info);
                    }
                    else if (data.code == ibpm.httpCode.fail) {
                        ibpm.httpErrorLog(data.info);
                        ibpm.alert.error(data.info);
                    }
                    else
                        callback(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    ibpm.httpErrorLog(textStatus);
                    ibpm.alert.warning(JSON.stringify(exres));
                },
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                },
                complete: function () {
                    ibpm.loading(false);
                }
            });
        },
        // post请求方法（FromForm）:url地址,param参数,callback回调函数
        httpAsyncPost: function (url, param, callback) {
            $.ajax({
                url: url,
                data: param,
                type: "POST",
                contentType: "application/x-www-form-urlencoded",
                dataType: "json",
                async: true,
                cache: false,
                success: function (data) {
                    if (data.code == ibpm.httpCode.exception) {
                        ibpm.httpErrorLog(data.info);
                        ibpm.alert.error(data.info);
                    }
                    else if (data.code == ibpm.httpCode.fail) {
                        ibpm.httpErrorLog(data.info);
                        ibpm.alert.error(data.info);
                    }
                    else
                        callback(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    ibpm.httpErrorLog(textStatus);
                    ibpm.alert.warning(JSON.stringify(exres));
                },
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                },
                complete: function () {
                    ibpm.loading(false);
                }
            });
        },
        httpAsyncPostEnc: function (url, param, callback) {
            $.ajax({
                url: url,
                data: param,
                type: "POST",
                //contentType: "application/json;charset=utf-8",    //加这句就验证不到
                dataType: "json",
                async: true,
                cache: false,
                success: function (data) {
                    if (data.code == ibpm.httpCode.exception) {
                        ibpm.httpErrorLog(data.info);
                        ibpm.alert.error(data.info);
                    }
                    else if (data.code == ibpm.httpCode.fail) {
                        ibpm.httpErrorLog(data.info);
                        ibpm.alert.error(data.info);
                    }
                    else
                        callback(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest.status);
                    alert(XMLHttpRequest.readyState);
                    alert(textStatus);
                },
                beforeSend: function () {
                },
                complete: function () {
                    ibpm.loading(false);
                }
            });
        },
        // post请求方法 FromBody（用于非验证提交）上不了RequestVerificationToken的验证
        httpAsyncPostBody: function (url, param, callback) {
            $.ajax({
                url: url,
                data: JSON.stringify(param),
                type: "POST",
                dataType: "json",
                contentType: "application/json",
                async: true,
                cache: false,
                success: function (data) {
                    if (data.code == ibpm.httpCode.exception) {
                        ibpm.httpErrorLog(data.info);
                        ibpm.alert.error(data.info);
                    }
                    else if (data.code == ibpm.httpCode.fail) {
                        ibpm.httpErrorLog(data.info);
                        ibpm.alert.error(data.info);
                    }
                    else
                        callback(data);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    ibpm.httpErrorLog(textStatus);
                    ibpm.alert.warning(JSON.stringify(exres));
                },
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                },
                complete: function () {
                    ibpm.loading(false);
                }
            });
        },
        // post同步
        httpSyncPost: function (url, param) {
            var RD = null;
            function getData(url, param) {
                var defer = $.Deferred();
                $.ajax({
                    url: url,
                    data: param,
                    type: "POST",
                    dataType: "json",
                    async: false,   //要求不能是异步
                    cache: false,
                    success: function (data) {
                        defer.resolve(data);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        defer.resolve(exres)
                    },
                    beforeSend: function (request) {
                        request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                    },
                    complete: function () {
                        ibpm.loading(false);
                    }
                });
                return defer.promise();
            }
            $.when(getData(url, param)).done(function (data) {
                RD = data;
            });
            return RD;
        },
        // ajax 异步封装
        httpAsync: function (mode, url, param, callback) {
            $.ajax({
                url: url,
                data: param,
                type: mode,
                dataType: "json",
                async: true,
                cache: false,
                success: function (res) {
                    if (res.code == ibpm.httpCode.success) {
                        callback(res.data);
                    }
                    else {
                        ibpm.httpErrorLog(res.info);
                        callback(null);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    ibpm.httpErrorLog(textStatus);
                    callback(null);
                },
                beforeSend: function (request) {
                    request.setRequestHeader("Authorization", "Bearer " + $.AToken);
                },
                complete: function () {
                    ibpm.loading(false);
                }
            });
        },
        deleteForm: function (url, param, callback) {
            ibpm.loading(true, '正在删除数据');
            setTimeout(function () {
                ibpm.httpAsyncPost(url, param, function (res) {
                    if (res.code == ibpm.httpCode.success) {
                        if (!!callback) {
                            callback(res);
                        }
                        ibpm.alert.success(res.info);
                    }
                    layer.close(layer.index);
                });
            }, 500);
        },
        postForm: function (url, param, callback) {
            ibpm.httpAsyncPost(url, param, function (res) {
                if (res.code == ibpm.httpCode.success) {
                    if (!!callback) {
                        callback(res);
                    }
                }
            });
        },
        ManageImg: function (PicNo) {
            ibpm.layerForm({
                id: 'layer_' + PicNo,  //id不能重复
                title: "图片管理",
                url: top.$.rootUrl + '/Annexes/ShowPic?id=' + PicNo,
                width: 900,
                height: 700,
                btn: null,
                maxmin: true
            });
        },
        ManageImgOnly: function (PicNo) {
            ibpm.layerForm({
                id: 'layer_Only_' + PicNo,  //id不能重复
                title: "图片浏览",
                url: top.$.rootUrl + '/Annexes/ShowOnlyPic?id=' + PicNo,
                width: 860,
                height: 620,
                btn: null,
                maxmin: true
            });
        }
    });
    //参数就是扩展对象
})(window.jQuery, top.ibpm);

//弹层（基于layer.js-3.0.3）
(function ($, ibpm) {
    "use strict";
    $.extend(ibpm, {
        // 询问框
        layerConfirm: function (_msg, callback) {
            top.ibpm.language.get(_msg, function (msg) {
                top.layer.confirm(msg, {
                    btn: ['确认', '取消'],
                    title: "系统提示",
                    icon: 0,
                    skin: 'M-layer',
                    success: function (layero, index) {
                        layero.find('.layui-layer-btn a').each(function () {
                            var $this = $(this);
                            var _text = $this.text();
                            top.ibpm.language.get(_text, function (text) {
                                $this.text(text);
                            });

                        });
                        layero.find('.layui-layer-title').each(function () {
                            var $this = $(this);
                            var _text = $this.text();
                            top.ibpm.language.get(_text, function (text) {
                                $this.text(text);
                            });

                        });
                    },
                }, function (index) {
                    callback(true, index);
                    top.layer.close(index); //再执行关闭 
                }, function (index) {
                    callback(false, index);
                    top.layer.close(index); //再执行关闭  
                });
            });
        },
        // 自定义表单弹层
        layerForm: function (op) {
            var dfop = {
                id: null,
                title: '系统窗口',
                width: 550,
                height: 400,
                url: 'error',
                btn: ['确认', '关闭'],
                callBack: false,
                maxmin: false,
                end: false,
            };
            $.extend(dfop, op || {});
            /*适应窗口大小*/
            dfop.width = dfop.width > $(window).width() ? $(window).width() - 10 : dfop.width;
            dfop.height = dfop.height > $(window).height() ? $(window).height() - 10 : dfop.height;

            var r = top.layer.open({
                id: dfop.id,
                maxmin: dfop.maxmin,
                type: 2,    //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                title: dfop.title,
                area: [dfop.width + 'px', dfop.height + 'px'],
                btn: dfop.btn,
                content: op.url,
                skin: dfop.btn == null ? 'M-layer-nobtn' : 'M-layer',
                success: function (layero, index) {
                    top['layer_' + dfop.id] = ibpm.iframe($(layero).find('iframe').attr('id'), top.frames);
                    layero[0].ibpm_layerid = 'layer_' + dfop.id;
                    //如果底部有按钮添加-确认并关闭窗口勾选按钮
                    if (!!dfop.btn && layero.find('.M-layer-btn-cb').length == 0) {
                        top.ibpm.language.get('确认并关闭窗口', function (text) {
                            layero.find('.layui-layer-btn').append('<div class="checkbox M-layer-btn-cb" myIframeId="layer_' + dfop.id + '" ><label><input checked="checked" type="checkbox" >' + text + '</label></div>');
                        });
                        layero.find('.layui-layer-btn a').each(function () {
                            var $this = $(this);
                            var _text = $this.text();
                            top.ibpm.language.get(_text, function (text) {
                                $this.text(text);
                            });
                        });
                    }
                    layero.find('.layui-layer-title').each(function () {
                        var $this = $(this);
                        var _text = $this.text();
                        top.ibpm.language.get(_text, function (text) {
                            $this.text(text);
                        });
                    });
                },
                yes: function (index) {
                    var flag = true;
                    if (!!dfop.callBack) {
                        flag = dfop.callBack('layer_' + dfop.id);
                    }
                    if (!!flag) {
                        ibpm.layerClose('', index);
                    }
                },
                end: function () {
                    top['layer_' + dfop.id] = null;
                    if (!!dfop.end) {
                        dfop.end();
                    }
                }
            });
        },
        // 关闭弹层
        layerClose: function (name, index) {
            var _index;
            if (!!index) {
                _index = index;
            }
            else {
                _index = top.layer.getFrameIndex(name);
            }
            var layero = top.$("#layui-layer" + _index);
            var $IsClose = layero.find('.layui-layer-btn').find(".M-layer-btn-cb input");
            var IsClose = $IsClose.is(":checked");
            if ($IsClose.length == 0) {
                IsClose = true;
            }
            if (IsClose) {
                top.layer.close(_index); //再执行关闭  
            } else {
                top[layero[0].ibpm_layerid].location.reload();
            }
        },        
    });
})(window.jQuery, top.ibpm);

